var express = require('express');
var bodyparser = require('body-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
var errorHandler = require('errorhandler');
// external options
var options = require('./options');
// initialize the express application
var app = express();
// apply logging
app.use(logger('dev'));
// apply body parsing
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended: false}));

// apply authentication
require('./auth.js')(app);

app.use(function (req, res, next) {
    res.set('Access-Control-Allow-Origin', '*');
    res.set('Access-Control-Allow-Credentials', true);
    res.set('Access-Control-Allow-Headers', 'token, DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding');

    next();
});

// apply routes
app.use('/', require('./routes/index.js'));
app.use('/user', require('./routes/user.js'));
app.use('/friend', require('./routes/friend.js'));
app.use('/question', require('./routes/question.js'));


// apply error output at development
if ('development' === app.get('env')) {
    app.use(errorHandler({dumpExceptions: true, showStack: true}));
}

// connect mongodb
mongoose.connect(options.mongoURL);

//app.set('port', options.expressPort);

module.exports = require('http').createServer(app);

